package org.springblade.modules.app.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.ijpay.core.enums.SignType;
import com.ijpay.core.enums.TradeType;
import com.ijpay.core.kit.WxPayKit;
import com.ijpay.wxpay.WxPayApi;
import com.ijpay.wxpay.model.UnifiedOrderModel;
import com.jpay.ext.kit.IpKit;
import com.jpay.ext.kit.StrKit;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.common.config.NoRepeatSubmit;
import org.springblade.common.config.WxPayConfig;
import org.springblade.common.utils.DecimalUtil;
import org.springblade.common.utils.JpushTemplate;
import org.springblade.common.utils.MoneyUtil;
import org.springblade.common.utils.smsutils.SMSUtils;
import org.springblade.common.utils.smsutils.UCPaasSMSConfig;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.DigestUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.app.dto.OrderAndDetailDTO;
import org.springblade.modules.app.dto.OrderAndToPayInfoDTO;
import org.springblade.modules.app.dto.OrderTjDTO;
import org.springblade.modules.app.entity.*;
import org.springblade.modules.app.service.*;
import org.springblade.modules.netty.NettyHandler;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 活动类型 表 控制器
 *
 * @author BladeX
 * @since 2020-08-24
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("blade-app/coal")
@Api(value = "活动类型 表", tags = "活动类型 表接口")
public class CoalController extends BladeController {

    private final ICoalService coalService;
    private final IOrderDetailService orderDetailService;
    private final IUserService userService;

    private final ICouponsConfigService couponsConfigService;

    private final INoticeService noticeService;

    private final IMoneyDetailService moneyDetailService;

    private final IOrderPoundageService orderPoundageService;

    private final IOrderCommentsService orderCommentsService;

    private final IJpushService jpushService;

    private final IHelpstarService helpstarService;


    ////所有可接的订单
    @GetMapping("/orderForWorkerCanAccept")
    public R<IPage<Order>> orderForWorkerCanAccept(Page page, Order coal) {
        BladeUser bladeUser = AuthUtil.getUser();
        User userInfo = userService.getById(bladeUser.getUserId());

        List<String> strings = Func.toStrList(userInfo.getQpccode());
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper();
        //TODO 后续只能接自己选的汽配城的订单校验
        queryWrapper.and(wrapper -> wrapper.eq(Order::getOrderstatus, "1"));
        queryWrapper.and(wrapper -> wrapper.in(Order::getCuserqpcid, strings));
        queryWrapper.orderByDesc(Order::getCtime);


        IPage<Order> pages = coalService.page(page, queryWrapper);
        for (Order entity : pages.getRecords()) {
            List<OrderDetail> orderDetailList = orderDetailService.list(new LambdaQueryWrapper<OrderDetail>().eq(OrderDetail::getOrderid, entity.getId()));
            entity.setOrderDetailList(orderDetailList);
        }

        return R.data(pages);
    }

    ////订单和订单明细
    @GetMapping("/getWyOrderByUser")
    public R getWyOrderByUser() {
        BladeUser bladeUser = AuthUtil.getUser();
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<Order>();
        queryWrapper.and(wrapper -> wrapper.eq(Order::getQxuserid, bladeUser.getUserId()));
        queryWrapper.and(wrapper -> wrapper.eq(Order::getOrderstatus, 5));
        queryWrapper.and(wrapper -> wrapper.eq(Order::getQxstatus, 2));
        List<Order> list = coalService.list(queryWrapper);
        if (list.size() > 0) {
            return R.data(400, list.get(0).getId(), "你有违约 订单未处理 请处理后再操作");
        } else {
            return R.success("");
        }
    }


    ////订单和订单明细
    @GetMapping("/orderAndDetails/{orderId}")
    public R<Order> orderAndDetails(@PathVariable Long orderId) {
        OrderAndDetailDTO orderAndDetailDTO = new OrderAndDetailDTO();
        Order order = coalService.getById(orderId);
        List<OrderDetail> orderDetailList = orderDetailService.list(new LambdaQueryWrapper<OrderDetail>().eq(OrderDetail::getOrderid, orderId));
        BeanUtils.copyProperties(order, orderAndDetailDTO);
        //查询已经选择的 orderDetailList

        List<String> pronotids = new ArrayList<>();
        for (OrderDetail entity : orderDetailList) {
            pronotids.add(entity.getProductid());
        }

        List<Helpstar> productList = helpstarService.list(new LambdaQueryWrapper<Helpstar>().notIn(Helpstar::getId, pronotids));

        for (Helpstar entity : productList) {
            OrderDetail single = new OrderDetail();
            single.setId(null);
            single.setProductid(entity.getId() + "");
            single.setPname(entity.getPname());
            single.setPcount(0);
            single.setPmoney(entity.getPmoney());
            single.setTotmoney(new BigDecimal(0.00));
            orderDetailList.add(single);
        }


        //查询没有选择的产品

        orderAndDetailDTO.setOrderDetailList(orderDetailList);
        //TODO 进三个月接单
//        if (!StringUtils.isEmpty(order.getWorkerid())) {
//            Integer valcount = workderOrder3Month(order);
//            if (StringUtils.isEmpty(valcount)) {
//                orderAndDetailDTO.setMonth3(0);
//            } else {
//                orderAndDetailDTO.setMonth3(valcount);
//            }
//        } else {
//            orderAndDetailDTO.setMonth3(0);
//        }
        OrderComments detail = orderCommentsService.getOne(new LambdaQueryWrapper<OrderComments>().eq(OrderComments::getOrderid, orderId));
        if (!StringUtils.isEmpty(detail)) {
            orderAndDetailDTO.setSfpjflag("1");
        } else {
            orderAndDetailDTO.setSfpjflag("2");
        }
        return R.data(orderAndDetailDTO);
    }

    @GetMapping("/orderAndDetailsWorkerInfo/{orderId}")
    public R<Order> orderAndDetailsWorkerInfo(@PathVariable Long orderId) {
        OrderAndDetailDTO orderAndDetailDTO = new OrderAndDetailDTO();
        Order order = coalService.getById(orderId);
        List<OrderDetail> orderDetailList = orderDetailService.list(new LambdaQueryWrapper<OrderDetail>().eq(OrderDetail::getOrderid, orderId));
        BeanUtils.copyProperties(order, orderAndDetailDTO);
        orderAndDetailDTO.setOrderDetailList(orderDetailList);
        //TODO 进三个月接单
        //TODO 进三个月接单
//        if (!StringUtils.isEmpty(order.getWorkerid())) {
//            Integer valcount = workderOrder3Month(order);
//            if (StringUtils.isEmpty(valcount)) {
//                orderAndDetailDTO.setMonth3(0);
//            } else {
//                orderAndDetailDTO.setMonth3(valcount);
//            }
//        } else {
//            orderAndDetailDTO.setMonth3(0);
//        }

        OrderComments detail = orderCommentsService.getOne(new LambdaQueryWrapper<OrderComments>().eq(OrderComments::getOrderid, orderId));
        if (!StringUtils.isEmpty(detail)) {
            orderAndDetailDTO.setSfpjflag("1");
        } else {
            orderAndDetailDTO.setSfpjflag("2");
        }
        return R.data(orderAndDetailDTO);
    }

    ///////////////////////////////////////////////商家创建订单//////////////////////////////////////////////
///////////////////////////////////////////////商家创建订单//////////////////////////////////////////////
    ////创建订单
    @NoRepeatSubmit
    @PostMapping("/merchantCreateOrder")
    public R merchantCreateOrder(@RequestBody OrderAndDetailDTO orderAndDetailDTO) {
        BladeUser bladeUser = AuthUtil.getUser();
        User userInfo = userService.getById(bladeUser.getUserId());
        if (!"2".equals(userInfo.getUsertype())) {
            return R.fail("你没有权限创建订单");
        }

        if (DecimalUtil.defineLessZeroGetTrue(orderAndDetailDTO.getOrderprice())) {
            log.error("资金安全日志: 金额为负数/谨防HK尝试恶意注入");
            return R.fail("资金安全日志: 金额为负数/谨防HK尝试恶意注入");
        }

        if (!StringUtils.isEmpty(orderAndDetailDTO.getDiscountprice())) {
            if (DecimalUtil.defineLessZeroGetTrue(orderAndDetailDTO.getDiscountprice())) {
                log.error("资金安全日志: 金额为负数/谨防HK尝试恶意注入");
                return R.fail("资金安全日志: 金额为负数/谨防HK尝试恶意注入");
            }
            int result1 = orderAndDetailDTO.getOrderprice().compareTo(orderAndDetailDTO.getDiscountprice());
            if (result1 == -1 || result1 == 0) {
                log.error("资金安全日志: 订单金额必须大于优惠券金额");
                return R.fail("资金安全日志: 订单金额必须大于优惠券金额");
            }
        }


        BigDecimal bigDecimalBy5000 = new BigDecimal(5000.00);
        int bigDecimalBy5000Res = orderAndDetailDTO.getOrderprice().compareTo(bigDecimalBy5000);
        if (bigDecimalBy5000Res == 1) {
            log.error("资金安全日志: 订单交易额过大请你核对后下单");
            return R.fail("资金安全日志: 订单交易额过大请你核对后下单");
        }

        Order order = new Order();
        BeanUtils.copyProperties(orderAndDetailDTO, order);
        //FIXME 前置判断条件
        if (StringUtils.isEmpty(order.getDiscountid())) {
            log.error("优惠券ID 没传 或者没有优惠券");
            order.setDiscountprice(new BigDecimal(0.00));
        }
        Long orderId = IdWorker.getId();
        order.setId(orderId);
        order.setFwname(userInfo.getName());
        order.setCuserid(userInfo.getId() + "");
        order.setCusername(userInfo.getName());
        order.setCuserphone(userInfo.getPhone());
        order.setCuseravatar(userInfo.getAvatar());
        order.setMerchno(orderId + "");
        order.setXdtime(new Date());
        List<OrderPoundage> list = orderPoundageService.list();
        //工人应收金额 下单价*(1-n%) n为扣率
        BigDecimal workerReceiveMoney = DecimalUtil.workderRealMoneyRegular(order.getOrderprice(), list.get(0).getPoundage());
        //FIXME payamount 为实际支付金额 订单金额 减去优惠券 --后续 实际支付动的金额工人可以改动     平台出补充差价给工人
        order.setPayamount(DecimalUtil.subtract(order.getOrderprice(), order.getDiscountprice()));

        if (DecimalUtil.defineLessZeroGetTrue(order.getPayamount())) {
            log.error("资金安全日志: 金额为负数/谨防HK尝试恶意注入");
            return R.fail("资金安全日志: 金额为负数/谨防HK尝试恶意注入");
        }

        order.setWorkerrealmoney(workerReceiveMoney);

        if (DecimalUtil.defineLessZeroGetTrue(workerReceiveMoney)) {
            log.error("资金安全日志: 金额为负数/谨防HK尝试恶意注入");
            return R.fail("资金安全日志: 金额为负数/谨防HK尝试恶意注入");
        }
        //FIXME 极光推送
        //FIXME 查询出所有的属于当前汽配城的工人
        LambdaQueryWrapper<User> queryWrapperByQpcWorker = new LambdaQueryWrapper();
        //TODO 后续只能接自己选的汽配城的订单校验
        queryWrapperByQpcWorker.and(wrapper -> wrapper.eq(User::getShstatus, "2"));
        queryWrapperByQpcWorker.and(wrapper -> wrapper.eq(User::getUsertype, "3"));
        queryWrapperByQpcWorker.and(wrapper -> wrapper.like(User::getQpccode, userInfo.getQpccode()));
        List<User> userlisByQpcWorder = userService.list(queryWrapperByQpcWorker);
        NettyHandler.handleOrderWorkerList(userlisByQpcWorder, userInfo.getName() + "商家已下单快来抢单");

        //FIXME 极光推送
        List<String> registerIds = new ArrayList<>();
        for (User entity : userlisByQpcWorder) {
            Jpush jpush = jpushService.getById(entity.getId());
            if (!StringUtils.isEmpty(jpush)) {
                registerIds.add(jpush.getRegistrationid());
            }
            //发送短信
            SMSUtils.testSendSms(UCPaasSMSConfig.MESSAGETTMPLATE_NOTICE_WORKER, userInfo.getName(), entity.getPhone());
        }
        JpushTemplate.pushMessage(registerIds, userInfo.getName() + "商家已下单快来抢单");


        order.setCuserqpcid(userInfo.getQpccode());
        order.setCuserqpname(userInfo.getQpcname());

        order.setOrderstatus("1");
        order.setDelflag("1");
        order.setCtime(new Date());


        boolean flag = coalService.save(order);
        if (flag) {
            List<OrderDetail> orderDetailList = orderAndDetailDTO.getOrderDetailList();
            for (OrderDetail orderDetail : orderDetailList) {
                orderDetail.setId(IdWorker.getId());
                orderDetail.setOrderid(orderId + "");
                orderDetailService.save(orderDetail);
            }
        }
        Order result = new Order();
        result.setId(orderId);
        return R.data(orderId);
    }

    /////商家订单列表
    @GetMapping("/merchantOrderPage")
    public R<IPage<Order>> merchantOrderPage(Page page, Order order) {
        BladeUser bladeUser = AuthUtil.getUser();
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.and(wrapper -> wrapper.eq(Order::getCuserid, bladeUser.getUserId()));
        if (!StringUtils.isEmpty(order.getOrderstatus())) {
            queryWrapper.and(wrapper -> wrapper.eq(Order::getOrderstatus, order.getOrderstatus()));
        }
        queryWrapper.orderByDesc(Order::getCtime);
        IPage<Order> pages = coalService.page(page, queryWrapper);
        for (Order entity : pages.getRecords()) {

            OrderComments detail = orderCommentsService.getOne(new LambdaQueryWrapper<OrderComments>().eq(OrderComments::getOrderid, entity.getId()));
            if (!StringUtils.isEmpty(detail)) {
                entity.setSfpjflag("1");
            } else {
                entity.setSfpjflag("2");
            }
            List<OrderDetail> orderDetailList = orderDetailService.list(new LambdaQueryWrapper<OrderDetail>().eq(OrderDetail::getOrderid, entity.getId()));
            entity.setOrderDetailList(orderDetailList);
        }
        return R.data(pages);
    }


    //////////商家取消订单
    @NoRepeatSubmit
    @PostMapping("/merchantCancleOrder/{orderId}")
    public synchronized R merchantCancleOrder(@PathVariable Long orderId) {
        BladeUser bladeUser = AuthUtil.getUser();
        User userInfo = userService.getById(bladeUser.getUserId());
        //校验
        if (StringUtils.isEmpty(orderId)) {
            return R.fail("订单主键 必传");
        }
        Order order = coalService.getById(orderId);

        if ("5".equals(order.getOrderstatus())) {
            return R.fail("已取消 当前无需操作");
        }
        if ("1".equals(order.getOrderstatus())) {
            order.setQxuserid(userInfo.getId() + "");
            order.setQxname(userInfo.getName());
            order.setOrderstatus("5");
            order.setQxstatus("1");
            boolean flag = coalService.updateById(order);
            //FIXME  通知消息 极光
            return R.status(flag);
        } else {
            order.setQxuserid(userInfo.getId() + "");
            order.setQxname(userInfo.getName());
            ////获取定义的违约金
            CouponsConfig couponsConfig = couponsConfigService.getOne(new LambdaQueryWrapper<CouponsConfig>().eq(CouponsConfig::getTypecode, "4"));
            order.setWymoney(couponsConfig.getCouponsmoney());
            order.setOrderstatus("5");
            order.setQxstatus("2");

            NettyHandler.handleOrderWorkerId(order.getWorkerid(), order.getCusername() + "商家已取消订单");

            Jpush jpush = jpushService.getById(order.getWorkerid());
            if (!StringUtils.isEmpty(jpush)) {
                List<String> list = new ArrayList<>();
                list.add(jpush.getRegistrationid());
                JpushTemplate.pushMessage(list, order.getCusername() + "商家已取消订单");
            }

            if (DecimalUtil.defineLessZeroGetTrue(order.getWymoney())) {
                log.error("资金安全日志: 金额为负数/谨防HK尝试恶意注入");
                return R.fail("资金安全日志: 金额为负数/谨防HK尝试恶意注入");
            }

            boolean flag = coalService.updateById(order);
            return R.status(flag);
        }
    }

    //////////商家预支付订单
    @NoRepeatSubmit
    @PostMapping("/merchantToPayOrder/{orderId}")
    public synchronized R merchantPayOrder(@PathVariable Long orderId) {
        BladeUser bladeUser = AuthUtil.getUser();
        User workerUserInfo = userService.getById(bladeUser.getUserId());

        OrderAndToPayInfoDTO orderAndToPayInfoDTO = new OrderAndToPayInfoDTO();

        if (StringUtils.isEmpty(orderId)) {
            return R.fail("订单主键 必传");
        }
        Order order = coalService.getById(orderId);


        if (DecimalUtil.defineLessZeroGetTrue(order.getOrderprice())) {
            log.error("资金安全日志: 金额为负数/谨防HK尝试恶意注入");
            return R.fail("资金安全日志: 金额为负数/谨防HK尝试恶意注入");
        }
        if (DecimalUtil.defineLessZeroGetTrue(order.getPayamount())) {
            log.error("资金安全日志: 金额为负数/谨防HK尝试恶意注入");
            return R.fail("资金安全日志: 金额为负数/谨防HK尝试恶意注入");
        }


        String ip = IpKit.getRealIp(getRequest());
        if (StrKit.isBlank(ip)) {
            ip = "127.0.0.1";
        }
        Map<String, String> params = UnifiedOrderModel
                .builder()
                .appid(WxPayConfig.appId)
                .mch_id(WxPayConfig.mchId)
                .nonce_str(WxPayKit.generateStr())
                .body("打木架")
                .attach("打木架")
                .out_trade_no(order.getId() + "")
                .total_fee(MoneyUtil.correctYuanToFen(order.getPayamount()) + "")
                .spbill_create_ip(ip)
                .notify_url(WxPayConfig.domain + "/blade-app/wxNotify/payOrderNotify")
                .trade_type(TradeType.APP.getTradeType())
                .build()
                .createSign(WxPayConfig.partnerKey, SignType.HMACSHA256);
        String xmlResult = WxPayApi.pushOrder(false, params);
        Map<String, String> result = WxPayKit.xmlToMap(xmlResult);
        String returnCode = result.get("return_code");
        String returnMsg = result.get("return_msg");
        if (!WxPayKit.codeIsOk(returnCode)) {
            return R.fail(returnMsg);
        }
        String resultCode = result.get("result_code");
        if (!WxPayKit.codeIsOk(resultCode)) {
            return R.fail(returnMsg);
        }
        // 以下字段在 return_code 和 result_code 都为 SUCCESS 的时候有返回
        String prepay_id = result.get("prepay_id");

        Map<String, String> packageParams = WxPayKit.appPrepayIdCreateSign(WxPayConfig.appId, WxPayConfig.mchId, prepay_id, WxPayConfig.partnerKey, SignType.HMACSHA256);
        order.setTopayid(prepay_id);

        BeanUtils.copyProperties(order, orderAndToPayInfoDTO);
        ///微信的
        String packagexxx = packageParams.get("package");
        String appid = packageParams.get("appid");
        String sign = packageParams.get("sign");
        String partnerid = packageParams.get("partnerid");
        String noncestr = packageParams.get("noncestr");
        String timestamp = packageParams.get("timestamp");

        orderAndToPayInfoDTO.setPackagexxx(packagexxx);
        orderAndToPayInfoDTO.setAppid(appid);
        orderAndToPayInfoDTO.setSign(sign);
        orderAndToPayInfoDTO.setPartnerid(partnerid);
        orderAndToPayInfoDTO.setNoncestr(noncestr);
        orderAndToPayInfoDTO.setTimestamp(timestamp);
        //平台摘要的 最好交互时 非https最好做双端签名和验签
        orderAndToPayInfoDTO.setUserdigestamp(DigestUtil.md5Hex(orderAndToPayInfoDTO.toString()));


        boolean flag = coalService.updateById(order);
        return R.data(orderAndToPayInfoDTO);
    }

    //////////商家支付违约金
    @NoRepeatSubmit
    @PostMapping("/merchantPayWyOrder/{orderId}")
    public synchronized R merchantPayWyOrder(@PathVariable Long orderId) {
        BladeUser bladeUser = AuthUtil.getUser();
        User merchantUserInfo = userService.getById(bladeUser.getUserId());
        OrderAndToPayInfoDTO orderAndToPayInfoDTO = new OrderAndToPayInfoDTO();
        if (StringUtils.isEmpty(orderId)) {
            return R.fail("订单主键 必传");
        }
        Order order = coalService.getById(orderId);


        if (!StringUtils.isEmpty(order.getWymoney()) && DecimalUtil.defineLessZeroGetTrue(order.getWymoney())) {
            log.error("资金安全日志: 金额为负数/谨防HK尝试恶意注入");
            return R.fail("资金安全日志: 金额为负数/谨防HK尝试恶意注入");
        }


//TODO 校验
        String ip = IpKit.getRealIp(getRequest());
        if (StrKit.isBlank(ip)) {
            ip = "127.0.0.1";
        }
        Map<String, String> params = UnifiedOrderModel
                .builder()
                .appid(WxPayConfig.appId)
                .mch_id(WxPayConfig.mchId)
                .nonce_str(WxPayKit.generateStr())
                .body("打木架")
                .attach("商家支付违约金")
                .out_trade_no(order.getId() + "")
                .total_fee(MoneyUtil.correctYuanToFen(order.getWymoney()) + "")
                .spbill_create_ip(ip)
                .notify_url(WxPayConfig.domain + "/blade-app/wxNotify/payOrderNotify")
                .trade_type(TradeType.APP.getTradeType())
                .build()
                .createSign(WxPayConfig.partnerKey, SignType.HMACSHA256);
        String xmlResult = WxPayApi.pushOrder(false, params);
        Map<String, String> result = WxPayKit.xmlToMap(xmlResult);
        String returnCode = result.get("return_code");
        String returnMsg = result.get("return_msg");
        if (!WxPayKit.codeIsOk(returnCode)) {
            return R.fail(returnMsg);
        }
        String resultCode = result.get("result_code");
        if (!WxPayKit.codeIsOk(resultCode)) {
            return R.fail(returnMsg);
        }
        // 以下字段在 return_code 和 result_code 都为 SUCCESS 的时候有返回
        String prepay_id = result.get("prepay_id");

        Map<String, String> packageParams = WxPayKit.appPrepayIdCreateSign(WxPayConfig.appId, WxPayConfig.mchId, prepay_id, WxPayConfig.partnerKey, SignType.HMACSHA256);
        order.setTopayid(prepay_id);

        BeanUtils.copyProperties(order, orderAndToPayInfoDTO);
        ///微信的
        String packagexxx = packageParams.get("package");
        String appid = packageParams.get("appid");
        String sign = packageParams.get("sign");
        String partnerid = packageParams.get("partnerid");
        String noncestr = packageParams.get("noncestr");
        String timestamp = packageParams.get("timestamp");

        orderAndToPayInfoDTO.setPackagexxx(packagexxx);
        orderAndToPayInfoDTO.setAppid(appid);
        orderAndToPayInfoDTO.setSign(sign);
        orderAndToPayInfoDTO.setPartnerid(partnerid);
        orderAndToPayInfoDTO.setNoncestr(noncestr);
        orderAndToPayInfoDTO.setTimestamp(timestamp);
        //平台摘要的 最好交互时 非https最好做双端签名和验签
        orderAndToPayInfoDTO.setUserdigestamp(DigestUtil.md5Hex(orderAndToPayInfoDTO.toString()));

        boolean flag = coalService.updateById(order);
        return R.data(orderAndToPayInfoDTO);
    }

///////////////////////////////////////////////工人端订单//////////////////////////////////////////////
///////////////////////////////////////////////工人端订单//////////////////////////////////////////////

    //////////工人抢单
    @NoRepeatSubmit
    @PostMapping("/workerAcceptOrder/{orderId}")
    public synchronized R workerAcceptOrder(@PathVariable Long orderId) {
        BladeUser bladeUser = AuthUtil.getUser();
        User userInfo = userService.getById(bladeUser.getUserId());
        //校验
        if (StringUtils.isEmpty(orderId)) {
            return R.fail("订单主键 必传");
        }
        //创建订单
        Order order = coalService.getById(orderId);

        if ("2".equals(order.getOrderstatus())) {
            return R.fail("未抢到.下次继续努力");
        }
        if ("3".equals(order.getOrderstatus()) || "4".equals(order.getOrderstatus()) || "5".equals(order.getOrderstatus())) {
            return R.fail("订单状态已变更 请刷新页面");
        }

        if (DecimalUtil.defineLessZeroGetTrue(order.getOrderprice())) {
            log.error("资金安全日志: 金额为负数/谨防HK尝试恶意注入");
            return R.fail("资金安全日志: 金额为负数/谨防HK尝试恶意注入");
        }
        //FIXME  通知消息 极光
        NettyHandler.handleOrderCuserd(order.getCuserid(), userInfo.getName() + "工人已抢单");
        Jpush jpush = jpushService.getById(order.getCuserid());
        if (!StringUtils.isEmpty(jpush)) {
            List<String> list = new ArrayList<>();
            list.add(jpush.getRegistrationid());
            JpushTemplate.pushMessage(list, userInfo.getName() + "工人已抢单");
        }

        order.setId(orderId);
        order.setWorkerid(userInfo.getId() + "");
        order.setWorkername(userInfo.getName());
        order.setWorkerphone(userInfo.getPhone());
        order.setWorkerjdtime(new Date());
        order.setWorkeravatar(userInfo.getAvatar());
        order.setWorkermyd(userInfo.getWorkermyd());
        order.setOrderstatus("2");
        boolean flag = coalService.updateById(order);
        return R.status(flag);
    }

    /////工人订单列表
    @GetMapping("/workerOrderPage")
    public R<IPage<Order>> workerOrderPage(Page page, Order order) {
        BladeUser bladeUser = AuthUtil.getUser();
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper();

        if ("4".equals(order.getOrderstatus())) {
            queryWrapper.and(wrapper -> wrapper.eq(Order::getOrderstatus, 4).or().eq(Order::getOrderstatus, 3));
        } else {
            queryWrapper.and(wrapper -> wrapper.eq(Order::getOrderstatus, order.getOrderstatus()));
        }
        queryWrapper.and(wrapper -> wrapper.eq(Order::getWorkerid, bladeUser.getUserId()));
        queryWrapper.orderByDesc(Order::getCtime);
        IPage<Order> pages = coalService.page(page, queryWrapper);


        for (Order entity : pages.getRecords()) {
            OrderComments detail = orderCommentsService.getOne(new LambdaQueryWrapper<OrderComments>().eq(OrderComments::getOrderid, entity.getId()));
            if (!StringUtils.isEmpty(detail)) {
                entity.setSfpjflag("1");
            } else {
                entity.setSfpjflag("2");
            }
            List<OrderDetail> orderDetailList = orderDetailService.list(new LambdaQueryWrapper<OrderDetail>().eq(OrderDetail::getOrderid, entity.getId()));
            entity.setOrderDetailList(orderDetailList);
        }
        return R.data(pages);
    }


    /////工人已完成订单
    @GetMapping("/workerComplateOrCancleOrderPage")
    public R<IPage<Order>> workerComplateOrderPage(Page page, Order order) {
        BladeUser bladeUser = AuthUtil.getUser();
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.and(wrapper -> wrapper.eq(Order::getOrderstatus, "4"));
        queryWrapper.and(wrapper -> wrapper.eq(Order::getWorkerid, bladeUser.getUserId()));
        queryWrapper.orderByDesc(Order::getCtime);
        IPage<Order> pages = coalService.page(page, queryWrapper);
        for (Order entity : pages.getRecords()) {
//            //TODO 进三个月接单
//            //TODO 进三个月接单
//            if (!StringUtils.isEmpty(order.getWorkerid())) {
//                Integer valcount = workderOrder3Month(order);
//                if (StringUtils.isEmpty(valcount)) {
//                    entity.setMonth3(0);
//                } else {
//                    entity.setMonth3(valcount);
//                }
//            }
            OrderComments detail = orderCommentsService.getOne(new LambdaQueryWrapper<OrderComments>().eq(OrderComments::getOrderid, entity.getId()));
            if (!StringUtils.isEmpty(detail)) {
                entity.setSfpjflag("1");
            } else {
                entity.setSfpjflag("2");
            }
            List<OrderDetail> orderDetailList = orderDetailService.list(new LambdaQueryWrapper<OrderDetail>().eq(OrderDetail::getOrderid, entity.getId()));
            entity.setOrderDetailList(orderDetailList);
        }
        return R.data(pages);
    }


    //    /////工人加单
    @NoRepeatSubmit
    @PostMapping("/workerAddOrder")
    public R workerAddOrder(@RequestBody OrderAndDetailDTO orderAndDetailDTO) {
        BladeUser bladeUser = AuthUtil.getUser();
        User workerUserInfo = userService.getById(bladeUser.getUserId());
        Order orderInfo = coalService.getById(orderAndDetailDTO.getId());


        if (DecimalUtil.defineLessZeroGetTrue(orderAndDetailDTO.getOrderprice())) {
            log.error("资金安全日志: 金额为负数/谨防HK尝试恶意注入");
            return R.fail("资金安全日志: 金额为负数/谨防HK尝试恶意注入");
        }


        if (!"2".equals(orderInfo.getOrderstatus())) {
            return R.fail("只有进行中的单子可修改");
        }


        BigDecimal newOrderPrice = new BigDecimal("0.00");
        for (OrderDetail orderDetail : orderAndDetailDTO.getOrderDetailList()) {
            BigDecimal totleMoney = DecimalUtil.multiply(orderDetail.getPmoney(), new BigDecimal(orderDetail.getPcount()));
            //FIXME 以后前后端 金额都必须计算 不要单独一端计算
//            newOrderPrice = DecimalUtil.add(newOrderPrice, orderDetail.getTotmoney());
            newOrderPrice = DecimalUtil.add(newOrderPrice, totleMoney);
        }

        BigDecimal bigDecimalBy5000 = new BigDecimal(5000.00);
        int bigDecimalBy5000Res = newOrderPrice.compareTo(bigDecimalBy5000);
        if (bigDecimalBy5000Res == 1) {
            log.error("资金安全日志: 订单交易额过大请你核对后加单");
            return R.fail("资金安全日志: 订单交易额过大请你核对后加单");
        }


        List<OrderPoundage> list = orderPoundageService.list();
        //工人应收金额 下单价*(1-n%) n为扣率
        BigDecimal workerReceiveMoney = DecimalUtil.workderRealMoneyRegular(newOrderPrice, list.get(0).getPoundage());
        //FIXME payamount 为实际支付金额 订单金额 减去优惠券 --后续 实际支付动的金额工人可以改动     平台出补充差价给工人
        orderInfo.setWorkerrealmoney(workerReceiveMoney);

        orderInfo.setOrderprice(newOrderPrice);
        orderInfo.setPayamount(DecimalUtil.subtract(newOrderPrice, orderInfo.getDiscountprice()));

        if (DecimalUtil.defineLessZeroGetTrue(workerReceiveMoney)) {
            log.error("资金安全日志: 金额为负数/谨防HK尝试恶意注入");
            return R.fail("资金安全日志: 金额为负数/谨防HK尝试恶意注入");
        }
        if (DecimalUtil.defineLessZeroGetTrue(orderInfo.getPayamount())) {
            log.error("资金安全日志: 金额为负数/谨防HK尝试恶意注入");
            return R.fail("资金安全日志: 金额为负数/谨防HK尝试恶意注入");
        }


        boolean flag = coalService.updateById(orderInfo);

        //FIXME  通知消息 极光 极光
        NettyHandler.handleOrderCuserd(orderInfo.getCuserid(), orderInfo.getWorkername() + "工人已加单");
        Jpush jpush = jpushService.getById(orderInfo.getCuserid());
        if (!StringUtils.isEmpty(jpush)) {
            List<String> registerIds = new ArrayList<>();
            registerIds.add(jpush.getRegistrationid());
            JpushTemplate.pushMessage(registerIds, orderInfo.getWorkername() + "工人已加单");
        }

        if (flag) {
            List<OrderDetail> orderDetailList = orderAndDetailDTO.getOrderDetailList();
            for (OrderDetail orderDetail : orderDetailList) {
                String strRegular = orderDetail.getId() + "";
                if (strRegular.length() < 5) {
                    orderDetail.setId(IdWorker.getId());
                }
                orderDetail.setOrderid(orderInfo.getId() + "");
                orderDetailService.saveOrUpdate(orderDetail);
            }
        }
        return R.success("加单成功");
    }

    /////工人修改订单价格
    @NoRepeatSubmit
    @PostMapping("/workerChangeOrderPrice")
    public R workerChangeOrderPrice(@RequestBody Order order) {
        BladeUser bladeUser = AuthUtil.getUser();
        User workerUserInfo = userService.getById(bladeUser.getUserId());
        if (StringUtils.isEmpty(order.getId())) {
            return R.fail("订单主键 必传");
        }
        Order orderInfo = coalService.getById(order.getId());
        if (!"2".equals(orderInfo.getOrderstatus())) {
            return R.fail("只能对进行中的订单操作");
        }
        if (!orderInfo.getWorkerid().equals(bladeUser.getUserId() + "")) {
            return R.fail("只有工人可修改订单价格");
        }

        if (DecimalUtil.defineLessZeroGetTrue(order.getOrderprice())) {
            log.error("资金安全日志: 金额为负数/谨防HK尝试恶意注入");
            return R.fail("资金安全日志: 金额为负数/谨防HK尝试恶意注入");
        }

        BigDecimal bigDecimalBy5000 = new BigDecimal(5000.00);
        int bigDecimalBy5000Res = order.getOrderprice().compareTo(bigDecimalBy5000);
        if (bigDecimalBy5000Res == 1) {
            log.error("资金安全日志: 订单交易额过大请你核对后修改");
            return R.fail("资金安全日志: 订单交易额过大请你核对后修改");
        }

        List<OrderPoundage> list = orderPoundageService.list();
        //工人应收金额 下单价*(1-n%) n为扣率
        BigDecimal workerReceiveMoney = DecimalUtil.workderRealMoneyRegular(order.getOrderprice(), list.get(0).getPoundage());
        //FIXME payamount 为实际支付金额 订单金额 减去优惠券 --后续 实际支付动的金额工人可以改动     平台出补充差价给工人
        orderInfo.setWorkerrealmoney(workerReceiveMoney);

        orderInfo.setOrderprice(order.getOrderprice());
        BigDecimal merchantRealPay = DecimalUtil.subtract(orderInfo.getOrderprice(), orderInfo.getDiscountprice());
        orderInfo.setPayamount(merchantRealPay);

        //FIXME  通知消息 极光 极光
        NettyHandler.handleOrderCuserd(orderInfo.getCuserid(), orderInfo.getWorkername() + "工人修改订单价格");
        Jpush jpush = jpushService.getById(orderInfo.getCuserid());
        if (!StringUtils.isEmpty(jpush)) {
            List<String> registerIds = new ArrayList<>();
            registerIds.add(jpush.getRegistrationid());
            JpushTemplate.pushMessage(registerIds, orderInfo.getWorkername() + "工人修改订单价格");
        }

        return R.status(coalService.updateById(orderInfo));
    }


    //////////工人取消订单
    @NoRepeatSubmit
    @PostMapping("/workerCancleOrder/{orderId}")
    public synchronized R workerCancleOrder(@PathVariable Long orderId) {
        BladeUser bladeUser = AuthUtil.getUser();
        User userInfo = userService.getById(bladeUser.getUserId());
        //校验
        if (StringUtils.isEmpty(orderId)) {
            return R.fail("订单主键 必传");
        }
        Order order = coalService.getById(orderId);


        //FIXME 防st恶意注入 安全金额参数必须大于等于0
        if (DecimalUtil.defineLessZeroGetTrue(order.getOrderprice())) {
            log.error("资金安全日志: 金额为负数/谨防HK尝试恶意注入");
            return R.fail("资金安全日志: 金额为负数/谨防HK尝试恶意注入");
        }


        if ("5".equals(order.getOrderstatus())) {
            return R.fail("已取消 当前无需操作");
        }
        order.setQxuserid(userInfo.getId() + "");
        order.setQxname(userInfo.getName());
        ////获取定义的违约金
        CouponsConfig couponsConfig = couponsConfigService.getOne(new LambdaQueryWrapper<CouponsConfig>().eq(CouponsConfig::getTypecode, "4"));
        order.setWymoney(couponsConfig.getCouponsmoney());
        order.setOrderstatus("5");
        order.setQxstatus("2");


        //FIXME 防st恶意注入 安全金额参数必须大于等于0
        if (DecimalUtil.defineLessZeroGetTrue(order.getWymoney())) {
            log.error("资金安全日志: 金额为负数/谨防HK尝试恶意注入");
            return R.fail("资金安全日志: 金额为负数/谨防HK尝试恶意注入");
        }


        boolean flag = coalService.updateById(order);
        //FIXME  通知消息 极光 极光
        NettyHandler.handleOrderCuserd(order.getCuserid(), order.getWorkername() + "工人取消订单");
        Jpush jpush = jpushService.getById(order.getCuserid());
        if (!StringUtils.isEmpty(jpush)) {
            List<String> list = new ArrayList<>();
            list.add(jpush.getRegistrationid());
            JpushTemplate.pushMessage(list, order.getWorkername() + "工人取消订单");
        }

        return R.status(flag);
    }

    //////////工人违约支付
    @NoRepeatSubmit
    @PostMapping("/workerPayWyOrder/{orderId}")
    public synchronized R workerPayWyOrder(@PathVariable Long orderId) {
        BladeUser bladeUser = AuthUtil.getUser();
        User userInfo = userService.getById(bladeUser.getUserId());

        OrderAndToPayInfoDTO orderAndToPayInfoDTO = new OrderAndToPayInfoDTO();

        if (StringUtils.isEmpty(orderId)) {
            return R.fail("订单主键 必传");
        }
        Order order = coalService.getById(orderId);
//TODO 校验
        //FIXME 防st恶意注入 安全金额参数必须大于等于0
        if (DecimalUtil.defineLessZeroGetTrue(order.getWymoney())) {
            log.error("资金安全日志: 金额为负数/谨防HK尝试恶意注入");
            return R.fail("资金安全日志: 金额为负数/谨防HK尝试恶意注入");
        }

        String ip = IpKit.getRealIp(getRequest());
        if (StrKit.isBlank(ip)) {
            ip = "127.0.0.1";
        }
        Map<String, String> params = UnifiedOrderModel
                .builder()
                .appid(WxPayConfig.appId)
                .mch_id(WxPayConfig.mchId)
                .nonce_str(WxPayKit.generateStr())
                .body("打木架")
                .attach("工人违约支付")
                .out_trade_no(order.getId() + "")
                .total_fee(MoneyUtil.correctYuanToFen(order.getWymoney()) + "")
                .spbill_create_ip(ip)
                .notify_url(WxPayConfig.domain + "/blade-app/wxNotify/payOrderNotify")
                .trade_type(TradeType.APP.getTradeType())
                .build()
                .createSign(WxPayConfig.partnerKey, SignType.HMACSHA256);
        String xmlResult = WxPayApi.pushOrder(false, params);
        Map<String, String> result = WxPayKit.xmlToMap(xmlResult);
        String returnCode = result.get("return_code");
        String returnMsg = result.get("return_msg");
        if (!WxPayKit.codeIsOk(returnCode)) {
            return R.fail(returnMsg);
        }
        String resultCode = result.get("result_code");
        if (!WxPayKit.codeIsOk(resultCode)) {
            return R.fail(returnMsg);
        }
        // 以下字段在 return_code 和 result_code 都为 SUCCESS 的时候有返回
        String prepay_id = result.get("prepay_id");

        Map<String, String> packageParams = WxPayKit.appPrepayIdCreateSign(WxPayConfig.appId, WxPayConfig.mchId, prepay_id, WxPayConfig.partnerKey, SignType.HMACSHA256);
        order.setTopayid(prepay_id);

        BeanUtils.copyProperties(order, orderAndToPayInfoDTO);
        ///微信的
        String packagexxx = packageParams.get("package");
        String appid = packageParams.get("appid");
        String sign = packageParams.get("sign");
        String partnerid = packageParams.get("partnerid");
        String noncestr = packageParams.get("noncestr");
        String timestamp = packageParams.get("timestamp");

        orderAndToPayInfoDTO.setPackagexxx(packagexxx);
        orderAndToPayInfoDTO.setAppid(appid);
        orderAndToPayInfoDTO.setSign(sign);
        orderAndToPayInfoDTO.setPartnerid(partnerid);
        orderAndToPayInfoDTO.setNoncestr(noncestr);
        orderAndToPayInfoDTO.setTimestamp(timestamp);
        //平台摘要的 最好交互时 非https最好做双端签名和验签
        orderAndToPayInfoDTO.setUserdigestamp(DigestUtil.md5Hex(orderAndToPayInfoDTO.toString()));


        boolean flag = coalService.updateById(order);
        return R.data(orderAndToPayInfoDTO);
    }

    //////////工人确认完工
    @NoRepeatSubmit
    @PostMapping("/workerComplateOrder/{orderId}")
    public synchronized R workerComplateOrder(@PathVariable Long orderId) {
        BladeUser bladeUser = AuthUtil.getUser();
        User userInfo = userService.getById(bladeUser.getUserId());
        //校验
        if (StringUtils.isEmpty(orderId)) {
            return R.fail("订单主键 必传");
        }
        Order order = coalService.getById(orderId);
        if ("3".equals(order.getOrderstatus())) {
            return R.fail("已完工 当前无需操作");
        }
        if ("1".equals(order.getOrderstatus()) || "3".equals(order.getOrderstatus()) || "4".equals(order.getOrderstatus()) || "5".equals(order.getOrderstatus())) {
            return R.fail("订单状态已变更 请刷新页面");
        }

        order.setOrderstatus("3");
        boolean flag = coalService.updateById(order);

        //FIXME  通知消息 极光
        NettyHandler.handleOrderCuserd(order.getCuserid(), order.getWorkername() + "工人确认完工");
        Jpush jpush = jpushService.getById(order.getCuserid());
        if (!StringUtils.isEmpty(jpush)) {
            List<String> list = new ArrayList<>();
            list.add(jpush.getRegistrationid());
            JpushTemplate.pushMessage(list, order.getWorkername() + "工人确认完工");
        }

        return R.status(flag);
    }


    /**
     * 详情
     */
    @GetMapping("/detail")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "详情", notes = "传入coal")
    public R<Order> detail(Order coal) {
        Order detail = coalService.getOne(Condition.getQueryWrapper(coal));
        return R.data(detail);
    }

    /**
     * 分页 活动类型 表
     */
    @GetMapping("/list")
    public R<IPage<Order>> list(Page page, Order coal) {
        BladeUser bladeUser = AuthUtil.getUser();
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.orderByDesc(Order::getCtime);
        IPage<Order> pages = coalService.page(page, queryWrapper);
        return R.data(pages);
    }


    /**
     * 自定义分页 活动类型 表
     */
    @GetMapping("/page")
    public R<IPage<Order>> page(Page page, Order coal) {
        BladeUser bladeUser = AuthUtil.getUser();
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.orderByDesc(Order::getCtime);
        IPage<Order> pages = coalService.page(page, queryWrapper);
        return R.data(pages);
    }


    /**
     * 新增 活动类型 表
     */
    @PostMapping("/save")
    public R save(@RequestBody Order coal) {
        return R.status(coalService.save(coal));
    }

    /**
     * 修改 活动类型 表
     */
    @PostMapping("/update")
    public R update(@RequestBody Order coal) {
        return R.status(coalService.updateById(coal));
    }

    /**
     * 新增或修改 活动类型 表
     */
    @PostMapping("/submit")
    public R submit(@RequestBody Order coal) {
        return R.status(coalService.saveOrUpdate(coal));
    }


    /**
     * 删除 活动类型 表
     */
    @PostMapping("/remove")
    public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
        return R.status(coalService.removeByIds(Func.toLongList(ids)));
    }


    ///////////////////////////////////////////统计的//////////////////////////////////////////////////


    public OrderTjDTO getThisMonth(User workerUerInfo) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");

        QueryWrapper<Order> queryWrappercm = new QueryWrapper<>();
        queryWrappercm.eq("workerid", workerUerInfo.getId());
        queryWrappercm.eq("orderstatus", "4");
        queryWrappercm.apply("date_format(ctime,'%Y-%m')={0}", sdf.format(new Date()));
        int complateCount = coalService.count(queryWrappercm);
        QueryWrapper<Order> queryWrappercn = new QueryWrapper<>();
        queryWrappercn.eq("workerid", workerUerInfo.getId());
        queryWrappercn.eq("orderstatus", "5");
        queryWrappercn.apply("date_format(ctime,'%Y-%m')={0}", sdf.format(new Date()));
        int cancleCount = coalService.count(queryWrappercn);

        QueryWrapper<MoneyDetail> queryWrappermk = new QueryWrapper<>();
        queryWrappermk.eq("skfuserid", workerUerInfo.getId());
        queryWrappermk.apply("date_format(ctime,'%Y-%m')={0}", sdf.format(new Date()));
        List<MoneyDetail> list = moneyDetailService.list(queryWrappermk);
        BigDecimal sumMoney = new BigDecimal("0.00");
        for (MoneyDetail entity : list) {
            sumMoney = DecimalUtil.add(sumMoney, entity.getTrademoney());
        }
        OrderTjDTO result = new OrderTjDTO();
        result.setComplatecount(complateCount);
        result.setCanclecount(cancleCount);
        result.setMakemoney(sumMoney.toString());
        result.setTjtitle(sdf.format(new Date()));
        return result;
    }

    private OrderTjDTO getBeforOneMonth(User workerUerInfo) {

        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.MONTH, -1);
        Date date = cal.getTime();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");

        QueryWrapper<Order> queryWrappercm = new QueryWrapper<>();
        queryWrappercm.eq("workerid", workerUerInfo.getId());
        queryWrappercm.eq("orderstatus", "4");
        queryWrappercm.apply("date_format(ctime,'%Y-%m')={0}", sdf.format(date));
        int complateCount = coalService.count(queryWrappercm);

        QueryWrapper<Order> queryWrappercn = new QueryWrapper<>();
        queryWrappercn.eq("workerid", workerUerInfo.getId());
        queryWrappercn.eq("orderstatus", "5");
        queryWrappercn.apply("date_format(ctime,'%Y-%m')={0}", sdf.format(date));
        int cancleCount = coalService.count(queryWrappercn);


        QueryWrapper<MoneyDetail> queryWrappermk = new QueryWrapper<>();
        queryWrappermk.eq("skfuserid", workerUerInfo.getId());
        queryWrappermk.apply("date_format(ctime,'%Y-%m')={0}", sdf.format(date));
        List<MoneyDetail> list = moneyDetailService.list(queryWrappermk);
        BigDecimal sumMoney = new BigDecimal("0.00");
        for (MoneyDetail entity : list) {
            sumMoney = DecimalUtil.add(sumMoney, entity.getTrademoney());
        }
        OrderTjDTO result = new OrderTjDTO();
        result.setComplatecount(complateCount);
        result.setCanclecount(cancleCount);
        result.setMakemoney(sumMoney.toString());
        result.setTjtitle(sdf.format(date));
        return result;
    }

    ///前两月
    private OrderTjDTO getBeforTwoMonth(User workerUerInfo) {

        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.MONTH, -2);
        Date date = cal.getTime();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");

        QueryWrapper<Order> queryWrappercm = new QueryWrapper<>();
        queryWrappercm.eq("workerid", workerUerInfo.getId());
        queryWrappercm.eq("orderstatus", "4");
        queryWrappercm.apply("date_format(ctime,'%Y-%m')={0}", sdf.format(date));
        int complateCount = coalService.count(queryWrappercm);
        QueryWrapper<Order> queryWrappercn = new QueryWrapper<>();
        queryWrappercn.eq("workerid", workerUerInfo.getId());
        queryWrappercn.eq("orderstatus", "5");
        queryWrappercn.apply("date_format(ctime,'%Y-%m')={0}", sdf.format(date));
        int cancleCount = coalService.count(queryWrappercn);


        QueryWrapper<MoneyDetail> queryWrappermk = new QueryWrapper<>();
        queryWrappermk.eq("skfuserid", workerUerInfo.getId());
        queryWrappermk.apply("date_format(ctime,'%Y-%m')={0}", sdf.format(date));
        List<MoneyDetail> list = moneyDetailService.list(queryWrappermk);
        BigDecimal sumMoney = new BigDecimal("0.00");
        for (MoneyDetail entity : list) {
            sumMoney = DecimalUtil.add(sumMoney, entity.getTrademoney());
        }
        OrderTjDTO result = new OrderTjDTO();
        result.setComplatecount(complateCount);
        result.setCanclecount(cancleCount);
        result.setMakemoney(sumMoney.toString());
        result.setTjtitle(sdf.format(date));
        return result;
    }

    ////月份订单
    public Integer workderOrder3Month(Order order) {
        User workerUerInfo = userService.getById(order.getWorkerid());
        List<OrderTjDTO> result = new ArrayList<>();
        OrderTjDTO by = getThisMonth(workerUerInfo);
        OrderTjDTO sy = getBeforOneMonth(workerUerInfo);
        OrderTjDTO qy = getBeforTwoMonth(workerUerInfo);
        result.add(by);
        result.add(sy);
        result.add(qy);
        Integer value = 0;
        for (OrderTjDTO entity : result) {
            value = value + entity.getComplatecount();
        }
        return value;
    }

}
